var Mongoose = require('mongoose'),
    util = require('../helpers/util');


var userLogSchema = Mongoose.Schema({
    user: {
        type: Mongoose.Schema.ObjectId,
        required: true,
        ref: 'User'
    },
    action: {
        type: String,
        default: ''
    },
    target: {
        type: String,
        default: ''
    }
}, {timestamps: true});

var userLog = Mongoose.model('userLog', userLogSchema);

userLog.createLog = function (newLog, callback) {
    newLog.save(callback);
};

userLog.getAllLogs = function (callback) {
    userLog.find({}, {createdAt: 1, action: 1, target: 1, _id: 0}, callback);
};

userLog.getUserLogsForTable = function (userId, callback) {
    userLog.find({user: Mongoose.Types.ObjectId(userId)}, {createdAt: 1, action: 1, target: 1, _id: 0}, callback);
};

userLog.getUserLogs = function (userId, callback) {
    userLog.find({user: Mongoose.Types.ObjectId(userId)}, callback);
};

userLog.getAllLogsByDate = function (params, callback) {

    var fromDate = util.getDateWithoutTimeStamp(params.fromDate);
    var todate1 = util.getDateWithoutTimeStamp(params.toDate);
    var endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));

    var searchMatch = {};

    if (params.userId == undefined) {
        searchMatch = {createdAt: {$gte: fromDate, $lt: endDate}};
    } else {
        searchMatch = {$and: [{createdAt: {$gte: fromDate, $lt: endDate}},{user: Mongoose.Types.ObjectId(params.userId)}]};
    }

    var skipItem = params.skipItem || 0,
        itemsperPage = params.itemsperPage || 10,
        sortParameter = 'createdAt',
        sortOrder = -1,
        sort = {},
        skip = parseInt(skipItem),
        limit = parseInt(itemsperPage);
    sort[sortParameter] = sortOrder;

    userLog.aggregate([
        {$match: searchMatch},
        {"$sort": sort},
        {"$skip": skip},
        {"$limit": limit},
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            $project:
            {
                "_id": "$_id",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "user": "$user",
                "target": "$target",
                "action": "$action",
                "createdAt": "$createdAt"
            }
        }
    ], callback);
};

userLog.getAllLogsByDateCount = function (params, callback) {

    var fromDate = util.getDateWithoutTimeStamp(params.fromDate);
    var todate1 = util.getDateWithoutTimeStamp(params.toDate);
    var endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));

    var searchMatch = {};

    if (params.userId == undefined) {
        searchMatch = {createdAt: {$gte: fromDate, $lt: endDate}};
    } else {
        searchMatch = {$and: [{createdAt: {$gte: fromDate, $lt: endDate}},{user: Mongoose.Types.ObjectId(params.userId)}]};
    }

    var sortParameter = 'createdAt',
        sortOrder = -1,
        sort = {};
    sort[sortParameter] = sortOrder;

    userLog.aggregate([
        {$match: searchMatch},
        {"$sort": sort},
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            $project:
            {
                "_id": "$_id",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "user": "$user",
                "target": "$target",
                "action": "$action",
                "createdAt": "$createdAt"
            }
        }
    ], callback);
};

userLog.getAllLogsCSV = function (params, callback) {
    var fromDate = util.getDateWithoutTimeStamp(params.fromDate);
    var todate1 = util.getDateWithoutTimeStamp(params.toDate);
    var endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));

    var searchMatch = {};

    if (params.userId == undefined) {
        searchMatch = {createdAt: {$gte: fromDate, $lt: endDate}};
    } else {
        searchMatch = {$and: [{createdAt: {$gte: fromDate, $lt: endDate}},{user: Mongoose.Types.ObjectId(params.userId)}]};
    }

    // userLog.find(searchMatch, callback);
    userLog.aggregate([
        {$match: searchMatch},
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            $project:
            {
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "user": "$user",
                "__v": "$__v",
                "target": "$target",
                "action": "$action",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]}
            }
        }
    ], callback);
};


module.exports = userLog;